package com.xunqi.activemq.queue;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.Test;

import javax.jms.*;
import java.io.IOException;

/**
 * @Description: 消费者延时消费
 * @Created: with IntelliJ IDEA.
 * @author: 夏沫止水
 * @createTime: 2020-06-26 10:31
 **/
public class JmsConsumer_DelayAndSchedule {

    //默认tcp协议
    public static final String ACTIVEMQ_URL = "tcp://192.168.77.130:61616";
    public static final String QUEUE_NAME = "Queue-延迟投递";

    @Test
    public void consumer() throws JMSException, IOException {

        System.out.println("我是1号消费者");

        //1、创建连接工厂,按照给定的url地址，采用默认的用户名和密码
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);

        //2、通过连接工厂，获得Collection并启动访问
        Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();

        //3、创建会话session
        //两个参数transacted=事务,acknowledgeMode=确认模式(签收)
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

        //4、创建目的地（具体是队列还是主题topic）
        Queue queue = session.createQueue(QUEUE_NAME);

        //5.创建消息的消费者,指定消费哪一个队列里面的消息
        MessageConsumer messageConsumer = session.createConsumer(queue);

        //同步阻塞
        while (true) {
            TextMessage textMessage = (TextMessage)messageConsumer.receive(4000L);

            if (null != textMessage) {
                System.out.println("*********消费者接受到消息：" + textMessage.getText());
                //手动签收
                textMessage.acknowledge();
            } else {
                break;
            }
        }

        //关闭资源
        messageConsumer.close();
        session.close();
        connection.close();



    }

}
